//tokenCenter.js
// 智能合约地址
import Web3 from "web3";
import {Message, Notification} from 'element-ui';
import {TokenCenterABI, TokenCenterAddress} from "./contractABI"
import {done, start} from "nprogress";
// 智能合约ABI
const tokenCenter = new Web3(Web3.givenProvider);
let contract;
export let MSGSENDER;
contract = new tokenCenter.eth.Contract(TokenCenterABI, TokenCenterAddress);

/**
 * 初始化
 * @param {Object} callback 返回账户地址
 */
function Init(callback) {
    //判断用户是否安装MetaMask钱包插件
    if (typeof window.ethereum === "undefined") {
        //没安装MetaMask钱包进行弹框提示
        alert("Looks like you need a Dapp browser to get started.");
        alert("Consider installing MetaMask!");
    } else {
        //如果用户安装了MetaMask，你可以要求他们授权应用登录并获取其账号       ethereum.enable()
        ethereum.enable()
            .catch(function (reason) {
                //如果用户拒绝了登录请求
                if (reason === "User rejected provider access") {
                    // 用户拒绝登录后执行语句；
                } else {
                    // 本不该执行到这里，但是真到这里了，说明发生了意外
                    alert("There was an issue signing you in.");
                }
            }).then(accounts => {
            setMsgSender(accounts[0])
            Notification.success("登录成功")
            //这里返回用户钱包地址
            callback(accounts[0]);

        });
    }
}
function getLeagueAddress(callback){
    contract.methods.leagueAddress().call()
        .then(r=>callback(r))
}
/**
 * 设置默认用户地址
 * @param option
 */
function setMsgSender(option) {
    MSGSENDER = option
}

/**
 * 获取Token Symbol 列表
 * @param callback  Token Symbol 列表
 */
function getTokenSymbolList(callback) {
    contract.methods.getTokenSymbol().call()
        .then(res => {
            callback(res)
        })
}

/**
 * 通过调用者 获取调用者的Token Address
 * @param callback Token Address
 */
function getTokenAddressByMSG(callback) {
    contract.methods.createrToken(MSGSENDER).call()
        .then(r => {
            callback(r)
        })
}

/**
 * 通过Token Symbol 获取 Exchange Address
 * @param option    Token Symbol
 * @param callback  Exchange Address
 */
function getExchangeAddressByTokenSymbol(option, callback) {
    contract.methods.tokenForExchange(option).call()
        .then(res => {
            callback(res)
        })
}

/**
 * 通过Token Address 获取 Exchange Address
 * @param option      Token Address
 * @param callback    Exchange Address
 */
function getExchangeAddressByTokenAddress(option, callback) {
    contract.methods.tokenToExchangeLookup(option).call()
        .then(res => {
            callback(res)
        })
}
function getTokenDetail(callback){
    this.getTokenAddressByMSG(tokenAddress=>{
        contract.methods.tokenInfos(tokenAddress).call()
            .then(r=>callback(r))
    })

}
/**
 *获取Token 的列表详情
 * @param callback
 */
function getTokenInfoList(callback) {
    contract.methods.getTokenListInfo().call()
        .then(res => {
            callback(res)
        })
}

/**
 * 创建Token
 * @param option  initialSupply 额度    tokenName 名字    tokenSymbol 标志
 * @param callback
 */
function tokenCreate(option, callback) {
    contract.methods.createToken(option.initialSupply, option.tokenName, option.tokenSymbol).send({from: MSGSENDER})
        .on('transactionHash', function (hash) {
            Message.success("您已提交一笔交易")
            start()
        })
        .on('confirmation', function (confirmationNumber, receipt) {

        })
        .on('receipt', function (receipt) {
            done()
            Message.success("您已交易成功")
            // Notification({
            //     title:"交易收据",
            //     type:"success",
            //     dangerouslyUseHTMLString: true,
            //     message: `<strong>交易哈希 <i style="color: cadetblue">${receipt.blockHash}</i></strong><br><strong>交易账号 <i style="color: cadetblue">${receipt.from}</i></strong><br><strong>交易总金额 <i style="color: cadetblue">-${receipt.gasUsed}</i></strong>`
            // })
            console.log(receipt)
            callback(true)
            // receipt 相关例子

        })
        .on('error', function (error, receipt) {
            // 如果交易被网络拒绝并带有交易收据，则第二个参数将是交易收据。
        })
}

/**
 * 销毁Token
 * @param option  initialSupply 额度    tokenName 名字    tokenSymbol 标志
 * @param callback
 */
function tokenBurn(option, callback) {
    contract.methods.burnToken(option.initialSupply, option.tokenName, option.tokenSymbol).send({from: MSGSENDER})
        .on('transactionHash', function (hash) {
            Message.success("您已提交一笔交易")
            start()
        })
        .on('confirmation', function (confirmationNumber, receipt) {

        })
        .on('receipt', function (receipt) {
            done()
            Message.success("您已交易成功")
            // Notification({
            //     title:"交易收据",
            //     type:"success",
            //     dangerouslyUseHTMLString: true,
            //     message: `<strong>交易哈希 <i style="color: cadetblue">${receipt.blockHash}</i></strong><br><strong>交易账号 <i style="color: cadetblue">${receipt.from}</i></strong><br><strong>交易总金额 <i style="color: cadetblue">-${receipt.gasUsed}</i></strong>`
            // })
            console.log(receipt)
            callback(true)
            // receipt 相关例子

        })
        .on('error', function (error, receipt) {
            // 如果交易被网络拒绝并带有交易收据，则第二个参数将是交易收据。
        })
}

//导出相应的方法
export default {
    Init,
    getLeagueAddress,
    setMsgSender,
    getTokenSymbolList,
    getExchangeAddressByTokenSymbol,
    getTokenInfoList,
    getExchangeAddressByTokenAddress,
    tokenCreate,
    tokenBurn,
    getTokenAddressByMSG,
    getTokenDetail,
}
